<template>
	<view>
		<view class="pet_box">
			<u-image :src="pet.avatar" width="100rpx" height="100rpx" radius="10rpx"></u-image>

			<view class="main">
				<view class="name">
					{{ pet.name }}
				</view>
				<view class="more">
					{{ pet.gender == 1 ? 'GG' : 'MM' }}/{{ pet.age }}岁
				</view>
			</view>
		</view>
		<view class="list">
			<view class="item" v-for="(item,index) in list" :key="index" :class="{to:item.from==userID}">
				<view class="top">
					<u-avatar size="60rpx" :src="item.avatar" v-if="item.from==userID"></u-avatar>
					<u-avatar size="60rpx" :src="head" v-else></u-avatar>
				</view>
				<view class="content">
					{{item.payload.text}}
					<view class="image_box" v-if="item.type=='TIMImageElem'">
						<u-image :src="item.payload.imageInfoArray[1].imageUrl" mode="" :key="index2"
							:width="item.payload.imageInfoArray[1].width+'rpx'" :height="item.payload.imageInfoArray[1].height+'rpx'"
							@click='showImage(item.payload.imageInfoArray[1].imageUrl)'></u-image>
					</view>

				</view>
			</view>
		</view>
		<!-- <view id="bottom" style="height: 200rpx;">

		</view> -->
		<view class="bottom_box">
			<!-- <view class="bottom_menu"> -->
			<!--				<view class="item">-->
			<!--					<u-image width="32rpx" height="32rpx"></u-image>-->
			<!--					<text>曾经问过</text>-->
			<!--				</view>-->
			<!--				<u-line length="40rpx" direction="col"></u-line>-->

			<!-- </view> -->
			<view class="submit">
				<view class="input">
					<input v-model="content" style="width: 100%;font-size: 28rpx;" cursor-spacing="20" border="none"
						placeholder="描述越详细，推荐越准，最少两字" />
				</view>
				<view @click="choose_image"
					style="width: 64rpx;height: 64rpx;border-radius: 50%;margin-left: 20rpx;background-color: #f3f4f6;overflow: hidden;">
					<u-image width="64rpx" height="64rpx"></u-image>
				</view>

				<view class="btn">
					<u-button text="发送" color="#FABB3C" @click="sendTextMessage" shape="circle"></u-button>
				</view>

			</view>

			<!--			<u-safe-bottom></u-safe-bottom>-->
		</view>



	</view>
</template>

<script>
	import {
		useAuthStore
	} from '@/store/modules/auth';
	import {
		ref
	} from 'vue';
	import {
		get_str
	} from '@/services/api/chat';
	import {
		doctorDetail
	} from '@/services/api/index'
	import TencentCloudChat from '@tencentcloud/chat';
	import TIMUploadPlugin from 'tim-upload-plugin';
	import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';
	const authStore = useAuthStore();
	const userInfo = ref();
	// import LibGenerateTestUserSig from '@/lib-generate-test-usersig-es.min.js';

	let options = {
		SDKAppID: 1600025073 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
	};
	// 创建 SDK 实例，`TencentCloudChat.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
	let chat = TencentCloudChat.create(options);


	chat.setLogLevel(1); // 普通级别，日志量较多，接入时建议使用
	// chat.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用


	// 注册腾讯云即时通信 IM 上传插件
	chat.registerPlugin({
		'tim-upload-plugin': TIMUploadPlugin
	});


	// 注册腾讯云即时通信 IM 本地审核插件
	chat.registerPlugin({
		'tim-profanity-filter-plugin': TIMProfanityFilterPlugin
	});

	export default {
		data() {
			return {
				list: [],
				name: '', //医生账号
				content: '',
				userID: '', //用户账号
				pet: {
					name: '',
					avatar: '',
					gender: '',
					age: '',
					id: '',

				},
				head:''
			}
		},
		methods: {
			//获取医生信息
			async getDoctor(id) {
				const res = await doctorDetail({
					id
				})
				this.head=res.data.avatar
			},
			showImage(img) {
				console.log(img)
				uni.previewImage({
					current: 0,
					urls: [img]
				})
			},
			async login() {
				let {
					data
				} = await get_str({
					type: 1
				})
				let userSig = data;
				console.log(userSig)

				let promise = chat.login({
					userID: this.userID,
					userSig: userSig
				});
				promise.then(imResponse => {
					if (imResponse.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录。
						this.chat.logout().then(res => {
							this.login()
						})
					} else {
						console.log('登录成功');
					}


				}).catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息

				});

			},
			onSdkReady() {
				this.onMessageReceived()
				this.up_userinfo()
			},
			onMessageReceived() {
				// console.log(e)
				let conversationID = `C2C${this.name}`
				chat.getMessageList({
					conversationID: conversationID
				}).then(res => {
					let mlist = [{
						payload: {
							text: "你好，有什么可以帮你"
						}
					}]
					this.list = mlist.concat(res.data.messageList);
					setTimeout(() => {
						uni.pageScrollTo({
							selector: '#bottom',
							scrollTop: '9999999999999999'
						});
					}, 1000)

					uni.pageScrollTo({
						selector: '#bottom',
						scrollTop: '9999999999999999'
					});
				})
			},
			sendTextMessage() {
				if (this.content == '') {
					return
				}
				// 发送文本消息，Web 端与小程序端相同
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = chat.createTextMessage({
					to: this.name,
					conversationType: TencentCloudChat.TYPES.CONV_C2C,
					// 消息优先级，用于群聊。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息
					// priority: TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL,
					payload: {
						text: this.content
					},
					// 如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
					needReadReceipt: false,
					cloudCustomData: {
						nick: this.name,
						content: this.content
					}
					// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
					// cloudCustomData: 'your cloud custom data'
				});
				// 2. 发送消息
				let promise = chat.sendMessage(message);
				promise.then(imResponse => {
					// 发送成功
					console.log(imResponse, '发送成功');
					this.content = '';
					this.onMessageReceived()
					// this.get_list()
				}).catch(imError => {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
			},
			choose_image() {
				uni.chooseImage({
					count: 1,
					success: e => {
						let url = e.tempFilePaths[0];
						console.log(url)
						this.send_image(e);
					}
				})
			},
			send_image(url) {
				let message = chat.createImageMessage({
					to: this.name,
					conversationType: TencentCloudChat.TYPES.CONV_C2C,
					// 消息优先级，用于群聊
					// priority: TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL,
					payload: {
						file: url,
					},
					// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
					// cloudCustomData: 'your cloud custom data'
					onProgress: function(event) {
						console.log('file uploading:', event)
					}
				});


				// 2. 发送消息
				let promise = chat.sendMessage(message);
				promise.then((imResponse) => {
					// 发送成功
					console.log(imResponse, '发送成功');
					this.onMessageReceived()
					// this.get_list()
				}).catch(function(imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});

			},
			up_userinfo() {
				var _this = this
				console.log(this.pet, 3445)
				console.log({
					nick: authStore.getUserInfo.nickname,
					avatar: authStore.getUserInfo.avatar,
					profileCustomField: [{
						key: "Tag_Profile_Custom_mobile",
						value: authStore.getUserInfo.mobile
					}, {
						key: "Tag_Profile_Custom_orderno",
						value: _this.pet.id
					}]
				}, 1231)

				let promise = chat.updateMyProfile({
					nick: authStore.getUserInfo.nickname,
					avatar: authStore.getUserInfo.avatar,
					profileCustomField: [{
						key: "Tag_Profile_Custom_mobile",
						value: authStore.getUserInfo.mobile
					}, {
						key: "Tag_Profile_Custom_orderno",
						value: _this.pet.id
					}]
				});
				promise.then(function(imResponse) {
					console.log(imResponse.data, '更新资料成功'); //
				}).catch(function(imError) {
					console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
				});

			},
		},

		async onLoad(option) {
			await authStore.getUserInfos();
			console.log(authStore.getUserInfo, 'authStore.getUserInfo')
			this.userID = `1_${authStore.getUserId}`
			if (option.id) {
				this.name = '2_' + option.id
				this.getDoctor(option.id)
			}
			if (option.doctorId) {
				this.name = '2_' + option.doctorId
				this.getDoctor(option.doctorId)
			}
			if (option.pet_id) {
				this.pet = {
					name: option.name,
					avatar: option.avatar,
					gender: option.gender,
					age: option.age,
					id: option.pet_id,
				}
			}
			// if(option.order_id){
			// 	this.pet ={
			// 		name:option.name,
			// 		avatar:option.avatar,
			// 		gender:option.gender,
			// 		age:option.age,
			// 		id:option.id,
			// 	}
			// }
			chat.on(TencentCloudChat.EVENT.SDK_READY, this.onSdkReady);
			chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
			await this.login()
			this.onMessageReceived()
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: 30vh;
		background-color: #F2F2F2;

	}

	.pet_box {
		position: sticky;
		z-index: 99;
		top: 0;
		left: 0;
		right: 0;
		padding: 32rpx;
		background-color: #fff;
		border-radius: 0 0 30rpx 30rpx;
		display: flex;
		align-items: center;

		.main {
			margin-left: 20rpx;

			.name {
				font-size: 28rpx;
				font-weight: bold;
			}

			.more {
				margin-top: 12rpx;
				color: #999999;
				font-size: 24rpx;
			}
		}
	}

	.list {
		.item {
			padding: 30rpx;
			// border-bottom: 1rpx solid #eee;
			display: flex;
			align-items: flex-start;

			.top {
				margin-right: 24rpx;

			}

			.content {
				// margin-top: 30rpx;
				padding: 30rpx;
				border-radius: 20rpx;
				background-color: #fff;
				font-size: 24rpx;
				display: inline-block;
			}
		}

		.to {
			flex-direction: row-reverse;

			.top {
				justify-content: flex-start;
				flex-direction: row-reverse;
				margin-right: 0;
				margin-left: 24rpx;
			}

			.content {
				background-color: #FABB3C;
				color: #fff;
			}
		}
	}

	.bottom_box {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;

		.bottom_menu {
			display: flex;
			height: 80rpx;
			align-items: center;
			border-bottom: 1rpx solid #eee;

			.item {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;

				text {
					margin-left: 12rpx;
					color: #222222;
					font-size: 28rpx;
				}
			}
		}
	}

	.submit {
		margin-top: 20rpx;
		display: flex;
		align-items: center;
		padding: 0 10rpx;
		padding-bottom: 40rpx;

		width: 750rpx;
		box-sizing: border-box;

		.input {
			height: 80rpx;
			flex: 1;
			background-color: #F5F5F5;
			display: flex;
			align-items: center;
			padding: 0 24rpx;
			border-radius: 40rpx;
		}

		.btn {
			width: 128rpx;
			margin-left: 16rpx;
			// margin-left: 30rpx;
		}
	}
</style>